package com.icim.xmtm005.importer.service;

import java.lang.reflect.InvocationTargetException;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.SqlDateConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.tags.EscapeBodyTag;

import com.icim.dao.RetTmCusG5PrdInDao;
import com.icim.dao.RetTmCusG5PrdIndtDao;
import com.icim.entity.Ret_tm_cus_g5_prd_in;
import com.icim.entity.Ret_tm_cus_g5_prd_indt;
import com.icim.exception.ICIMException;
import com.icim.util.TimeUtil;
import com.icim.xmtm005.dao.CtSlimifshipbox005Dao;
import com.icim.xmtm005.dao.CtSlimifshipproduct005Dao;
import com.icim.xmtm005.entity.CtSlimifShipProduct005;
import com.icim.xmtm005.entity.CtSlimifshipbox005;

@Service("xmtmImportProductIn005Service")
public class XmtmImportProductIn005Service implements IXmtmImportProductIn005Service {

	private static final Logger logger = LoggerFactory
			.getLogger(XmtmImportProductIn005Service.class);

	@Resource
	private JdbcTemplate xmtm005JdbcTemplate;

	@Resource
	private CtSlimifshipbox005Dao ctSlimifshipbox005Dao;

	@Resource
	private CtSlimifshipproduct005Dao ctSlimifshipproduct005Dao;

	@Resource
	private RetTmCusG5PrdInDao retTmCusG5PrdInDao;

	@Resource
	private RetTmCusG5PrdIndtDao retTmCusG5PrdIndtDao;

	public void setErrorMessage(CtSlimifshipbox005 fromBox, ICIMException ex) {
	    String message = ex.getMessage()==null ? "":ex.getMessage();
		ctSlimifshipbox005Dao.updateBoxReceiveflag(fromBox.getBoxname(), "N",
				TimeUtil.getCurrentTimestamp(), message);
	}

	@Override
	public void subMainProc() throws IllegalAccessException,
			InvocationTargetException {

		/*
		 * get boxes havn't received
		 */
	    logger.info("005 importer job starting ......");
		List<CtSlimifshipbox005> fromBoxList = ctSlimifshipbox005Dao.queryNewBox("WG");//TODO

		/*
		 * loop boxes and get sheets in the box save sheets and save box
		 * 
		 * save one , commit one. if commmit success ==>update custom's record
		 * status. if error occurred ==> update custom's record errormessage
		 * column;
		 */

		for (CtSlimifshipbox005 fromBox : fromBoxList) {

			ICIMException icimException = null;

			try {

				subMainProc2(fromBox);

			} catch (Exception ex) {
			    logger.error("005subMainProc2异常："+ex.getMessage());
				logger.error(ex.toString());
				icimException = new ICIMException(ex.getMessage(), ex);
			} finally {

				if (icimException != null) {
					setErrorMessage(fromBox, icimException);
				} else {
					ctSlimifshipbox005Dao.updateBoxReceiveflag(
							fromBox.getBoxname(), "Y",
							TimeUtil.getCurrentTimestamp(), "");
				}
			}

			logger.info("import successful");

		}

	}

	@Transactional("icimTransactionManager")
	private void subMainProc2(CtSlimifshipbox005 fromBox)
			throws IllegalAccessException, InvocationTargetException {
		String boxId = fromBox.getBoxname();

		List<CtSlimifShipProduct005> fromSheetList = ctSlimifshipproduct005Dao
				.listSheets(boxId,"WG");//TODO

		ConvertUtils.register(new SqlDateConverter(null), Date.class);
		ConvertUtils.register(new SqlDateConverter(null), Timestamp.class);

		for (CtSlimifShipProduct005 fromSheet : fromSheetList) {
			Ret_tm_cus_g5_prd_indt toSheet = new Ret_tm_cus_g5_prd_indt();
			logger.info("fromSheet:["+fromSheet.getProductname()+"],物理箱号："+fromSheet.getBoxrealid());
			BeanUtils.copyProperties(toSheet, fromSheet);
			String productname = toSheet.getProductname();
			toSheet.setBoxrealid(fromSheet.getBoxrealid());
			if (retTmCusG5PrdIndtDao.get(productname) == null) {
			    logger.info("indt开始新增:["+fromSheet.getProductname()+"],物理箱号："+toSheet.getBoxrealid());
				retTmCusG5PrdIndtDao.save(toSheet);
			} else {
			    logger.info("indt开始更新:["+fromSheet.getProductname()+"],物理箱号："+toSheet.getBoxrealid());
				retTmCusG5PrdIndtDao.update(toSheet);
			}

		}

		Ret_tm_cus_g5_prd_in toBox = retTmCusG5PrdInDao.get(boxId);
		if (toBox == null) {
			toBox = new Ret_tm_cus_g5_prd_in();
			BeanUtils.copyProperties(toBox, fromBox);
			toBox.setEventtime(fromBox.getEventtime());
			toBox.setDeliverytime(fromBox.getDeliverytime());
			toBox.setReceivestate("INSERT");
			toBox.setErrormessage("");
			toBox.setReceiveflag("Y");
			toBox.setBoxrealid(fromBox.getBoxrealid());
			retTmCusG5PrdInDao.save(toBox);
		} else {
			BeanUtils.copyProperties(toBox, fromBox);
			toBox.setEventtime(fromBox.getEventtime());
			toBox.setDeliverytime(fromBox.getDeliverytime());
			toBox.setReceivestate("UPDATE");
			toBox.setErrormessage("");
			toBox.setReceiveflag("Y");
			toBox.setBoxrealid(fromBox.getBoxrealid());
			retTmCusG5PrdInDao.update(toBox);
		}
	}
}
